package com.jbit.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jbit.common.ErrorCodeEnum;
import com.jbit.exception.ServiceException;
import com.jbit.pojo.User;
import com.jbit.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 大坑  必须重写此方法，不然shiro会报错
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     * 只有当需要检测用户权限的时候才会调用此方法 例如checkRole  checkPermission之类的
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (token == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_TOKEN_IS_EMPTY);
        }

        // 解密获得username，用于和数据库进行对比
        String username = jwtTokenUtil.getUserNameFromToken(token);
        if (StringUtils.isEmpty(username)) {
            throw new ServiceException(ErrorCodeEnum.AUTH_UNKNOWN);
        }
        //根据userCode去数据库比较
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserCode, username);
        User userBean = userService.getOne(wrapper);
        if (userBean == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }

        if (!jwtTokenUtil.validateToken(token, username)) {
            throw new AuthenticationException(" token过期或者无效，请重新登入！");
        }

        if (userBean.getActivated() == 0) {
            throw new LockedAccountException("账号未激活!");
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
